﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GreenyMeter.DOM.Objets;
using System.Data;

namespace GreenyMeter
{
    public partial class YourHealth : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["isLogged"] == null)
            {
                Response.Redirect("ComingSoon.aspx", true);

            }

            if (!IsPostBack)
            {
                string strScramble = Request.QueryString["find"];

                if (Session["p1"] == null)
                {
                    Session["p1"] = 0;
                    Session["p2"] = 100;

                }
                if (strScramble == "Details") { setCalculateStyles(true); } else { setCalculateStyles(false); }

                divIngredients.Visible = false;

            }
        }

        protected void DropDownListSearchType1_SelectedIndexChanged(object sender, EventArgs e)
        {
            LabelStepsHeaderText.Text = "1. Indicanos el tipo de busqueda.";
            LabelStepDescriptionText.Text = "Puede ser un producto, un alimento o puedes intentar buscar por la marca del producto.";
            DropDownListSearchType2.Visible = false;
            DropDownListSearchType3.Visible = false;
            TextBoxSearchByProduct.Visible = false;
            RepeaterIngredientList1.DataSource = null;
            RepeaterIngredientList2.DataSource = null;
            RepeaterIngredientList1.DataBind();
            RepeaterIngredientList2.DataBind();
            divIngredients.Visible = false;

            ButtonSearch.Visible = false;
            bindSearchType2(Convert.ToInt16(DropDownListSearchType1.SelectedValue));

        }

        private void bindSearchType2(Int16 SearchType1Id)
        {



            if (SearchType1Id == 0)
            {
                DropDownListSearchType2.Visible = false;
                TextBoxSearchByProduct.Visible = false;
                ButtonSearch.Visible = false;
                RepeaterIngredientList1.Visible = false;
                RepeaterIngredientList2.Visible = false;
            }
            else if (SearchType1Id == 1) //bindFoodCategories
            {
                LabelStepDescriptionText.Text = "Los alimentos se dividen en categorias. Selecciona una para hacer mas facil tu búsqueda.";
                DropDownListSearchType2.Visible = true;
                DropDownListSearchType2.DataSource = Food.getAllFoodCategories();
                DropDownListSearchType2.DataTextField = "FoodCategoryName";
                DropDownListSearchType2.DataValueField = "FoodCategoryId";
                DropDownListSearchType2.DataBind();

            }
            else if (SearchType1Id == 2) //bindProductCategories
            {
                LabelStepDescriptionText.Text = "Los productos se dividen en categorias. Selecciona una para hacer mas facil tu búsqueda.";
                DropDownListSearchType2.Visible = true;
                DropDownListSearchType2.DataSource = Products.getAllProductCategories();
                DropDownListSearchType2.DataTextField = "ProductCategoryName";
                DropDownListSearchType2.DataValueField = "ProductCategoryId";
                DropDownListSearchType2.DataBind();
            }
            else if (SearchType1Id == 3) //bindProductCategories
            {
                LabelStepDescriptionText.Text = "Escribe la marca de tu producto, es posible que se encuentre en nuestro sistema.";
                TextBoxSearchByProduct.Visible = true;
                ButtonSearch.Visible = true;
            }

        }

        private void bindSearchType3(Int16 SearchType1Id, Int32 SearchType2Id)
        {
            RepeaterIngredientList1.Visible = false;
            RepeaterIngredientList2.Visible = false;
            if (SearchType1Id == 0)
            {
                DropDownListSearchType2.Visible = false;
                DropDownListSearchType3.Visible = false;


            }
            else if (SearchType1Id == 1)
            {
                LabelStepDescriptionText.Text = "Ahora selecciona un tipo de alimento, ya casi esta completa la infromación.";
                bindFoodTypes();

            }
            else if (SearchType2Id == 2)
            {
                LabelStepDescriptionText.Text = "Ahora selecciona un tipo de producto, ya casi esta completa la infromación.";
                bindProductTypes();
            }

        }

        private void bindProductTypes()
        {
            DropDownListSearchType3.Visible = true;
            DropDownListSearchType3.DataSource = Products.getProductTypesByCategoryId(Int32.Parse(DropDownListSearchType2.SelectedValue));
            DropDownListSearchType3.DataTextField = "ProductTypeName";
            DropDownListSearchType3.DataValueField = "ProductTypeId";
            DropDownListSearchType3.DataBind();

        }

        private void bindFoodTypes()
        {
            DropDownListSearchType3.Visible = true;
            DropDownListSearchType3.DataSource = Food.getFoodTypesByCategoryId(Int32.Parse(DropDownListSearchType2.SelectedValue));
            DropDownListSearchType3.DataTextField = "FoodTypeName";
            DropDownListSearchType3.DataValueField = "FoodTypeId";
            DropDownListSearchType3.DataBind();

        }

        protected void DropDownListSearchType2_SelectedIndexChanged(object sender, EventArgs e)
        {
            RepeaterIngredientList1.DataSource = null;
            RepeaterIngredientList2.DataSource = null;
            RepeaterIngredientList1.DataBind();
            RepeaterIngredientList2.DataBind();
            divIngredients.Visible = false;
            bindSearchType3(Convert.ToInt16(DropDownListSearchType1.SelectedValue), Convert.ToInt32(DropDownListSearchType2.SelectedValue));

        }

        protected void DropDownListSearchType3_SelectedIndexChanged(object sender, EventArgs e)
        {
            LabelStepsHeaderText.Text = "2. Selecciona los ingredientes.";
            LabelStepDescriptionText.Text = "Los ingredientes pertenecen a diversos sub-grupos, pueden ser ingredientes básicos, aditivos o conservantes, esto define que tan verde es lo que estas consultando.";
            LabelMessage.Text = "Ahora selecciona los ingredientes que contiene tu alimento.";
            BindIngredientBoxes();

        }

        public void BindIngredientBoxes()
        {
            DataTable dtIngredientList = Food.usp_getIngredientTypesByFoodTypeId(Int32.Parse(DropDownListSearchType3.SelectedValue));

            dtIngredientList.Columns.Add("servType", typeof(string));
            dtIngredientList.Columns.Add("iconType", typeof(string));


            if (dtIngredientList != null)
            {

                if (dtIngredientList.Rows.Count > 0)
                {
                    RepeaterIngredientList1.Visible = true;
                    RepeaterIngredientList2.Visible = true;
                    divIngredients.Visible = true;

                    DataTable dtIngredientList1 = dtIngredientList.Clone();
                    DataTable dtIngredientList2 = dtIngredientList.Clone();

                    foreach (DataRow row in dtIngredientList.Rows)
                    {


                        if (dtIngredientList.Rows.IndexOf(row) % 4 == 0)
                        {
                            row["servType"] = "serv-a";
                            row["iconType"] = "icon-gift";
                            DataRow NewRow = dtIngredientList1.NewRow();
                            NewRow.ItemArray = row.ItemArray;
                            dtIngredientList1.Rows.Add(NewRow);

                        }
                        else if (dtIngredientList.Rows.IndexOf(row) % 4 == 1)
                        {
                            row["servType"] = "serv-b";
                            row["iconType"] = "icon-home";
                            DataRow NewRow = dtIngredientList1.NewRow();
                            NewRow.ItemArray = row.ItemArray;
                            dtIngredientList1.Rows.Add(NewRow);
                        }
                        else if (dtIngredientList.Rows.IndexOf(row) % 4 == 2)
                        {
                            row["servType"] = "serv-a";
                            row["iconType"] = "icon-bullhorn";
                            DataRow NewRow = dtIngredientList2.NewRow();
                            NewRow.ItemArray = row.ItemArray;
                            dtIngredientList2.Rows.Add(NewRow);
                        }
                        else
                        {
                            row["servType"] = "serv-b";
                            row["iconType"] = "icon-cloud";
                            DataRow NewRow = dtIngredientList2.NewRow();
                            NewRow.ItemArray = row.ItemArray;
                            dtIngredientList2.Rows.Add(NewRow);
                        }

                        RepeaterIngredientList1.DataSource = dtIngredientList1;
                        RepeaterIngredientList2.DataSource = dtIngredientList2;

                        RepeaterIngredientList1.DataBind();
                        RepeaterIngredientList2.DataBind();

                        foreach (RepeaterItem ri in RepeaterIngredientList1.Items)
                        {
                            CheckBoxList CheckBoxListIngredientsGetValues = (CheckBoxList)ri.FindControl("CheckBoxListIngredients1");
                            DataTable dtIngredients = Food.getFoodIngredientsByIngredientTypeId(Int16.Parse(dtIngredientList1.Rows[ri.ItemIndex]["IngredientTypeId"].ToString()));
                            CheckBoxListIngredientsGetValues.DataSource = dtIngredients;

                            CheckBoxListIngredientsGetValues.DataValueField = "IngredientTypeId";
                            CheckBoxListIngredientsGetValues.DataTextField = "IngredientName";

                            CheckBoxListIngredientsGetValues.DataBind();

                            int i = 0;
                            foreach (ListItem item in CheckBoxListIngredientsGetValues.Items)
                            {

                                if (dtIngredients.Rows[i]["isSelected"].ToString() == "True")
                                {
                                    item.Selected = true;
                                }
                                i++;
                            }
                            //CheckBoxListIngredientsGetValues.DataBind();

                        }
                        foreach (RepeaterItem ri in RepeaterIngredientList2.Items)
                        {
                            CheckBoxList CheckBoxListIngredientsGetValues = (CheckBoxList)ri.FindControl("CheckBoxListIngredients2");

                            CheckBoxListIngredientsGetValues.DataSource = Food.getFoodIngredientsByIngredientTypeId(Int16.Parse(dtIngredientList2.Rows[ri.ItemIndex]["IngredientTypeId"].ToString()));

                            CheckBoxListIngredientsGetValues.DataValueField = "IngredientTypeId";
                            CheckBoxListIngredientsGetValues.DataTextField = "IngredientName";
                            CheckBoxListIngredientsGetValues.DataBind();

                        }

                    }

                }
                else
                {

                    RepeaterIngredientList1.DataSource = null;
                    RepeaterIngredientList2.DataSource = null;
                    RepeaterIngredientList1.DataBind();
                    RepeaterIngredientList2.DataBind();
                    divIngredients.Visible = false;

                }

            }


        }

        protected void ButtonCalculate_Click(object sender, EventArgs e)
        {
            if (divIngredients.Visible == true)
            {
                Calculate();
                ButtonCalculate.Enabled = true;
            }
            else {
                ButtonCalculate.Enabled = false;
            }

        }

        public void Calculate()
        {

            int suma = 0;
            int prom = 0;
            int items = 0;
            DataTable dtIngredientList = Food.usp_getIngredientTypesByFoodTypeId(Int32.Parse(DropDownListSearchType3.SelectedValue));

            if (dtIngredientList.Rows.Count > 0)
            {

                foreach (RepeaterItem ri in RepeaterIngredientList1.Items)
                {
                    CheckBoxList CheckBoxListIngredientsGetValues = (CheckBoxList)ri.FindControl("CheckBoxListIngredients1");

                    //DataTable dtIngredients = Food.getFoodIngredientsByIngredientTypeId(Int16.Parse(dtIngredientList.Rows[ri.ItemIndex]["IngredientTypeId"].ToString()));
                    DataTable dtIngredients = Food.getFoodIngredientsByIngredientTypeId(Int16.Parse(CheckBoxListIngredientsGetValues.Items[0].Value));
                    int i = 0;
                    foreach (ListItem listItem in CheckBoxListIngredientsGetValues.Items)
                    {
                        if (listItem.Selected)
                        {
                            if (dtIngredients.Rows[i]["IngredientScore"].ToString() != string.Empty)
                            {
                                suma = suma + Int16.Parse(dtIngredients.Rows[i]["IngredientScore"].ToString());
                                items = items + i;
                            }

                        }
                        i = i + 1;
                    }

                }

                foreach (RepeaterItem ri in RepeaterIngredientList2.Items)
                {
                    CheckBoxList CheckBoxListIngredientsGetValues = (CheckBoxList)ri.FindControl("CheckBoxListIngredients2");

                    DataTable dtIngredients = Food.getFoodIngredientsByIngredientTypeId(Int16.Parse(CheckBoxListIngredientsGetValues.Items[0].Value));
                    int i = 0;
                    foreach (ListItem ItemIndex in CheckBoxListIngredientsGetValues.Items)
                    {
                        if (ItemIndex.Selected)
                        {
                            if (dtIngredients.Rows[i]["IngredientScore"].ToString() != string.Empty)
                            {
                                suma = suma + Int16.Parse(dtIngredients.Rows[i]["IngredientScore"].ToString());
                                items = items + i;
                            }
                        }
                        i = i + 1;
                    }

                }

                prom = suma / items;
                updatePanelCalculate.Update();
                Session["p1"] = prom;
                Session["p2"] = prom;
                setCalculateStyles(false);
            }
            else { LabelStepDescriptionText.Text = "La seleccion no contiene ingredientes"; }
        }

        public void setCalculateStyles(bool details)
        {
            //scriptm("$(document).ready(function (){ alert('hola'); });");


            if ((int)Session["p1"] != 0)
            {

                yourHealthCircle.Attributes.Add("style", "border:7px solid #6EA808");

            }

            scriptm("$(document).ready(function (){ $('#g1').click(function (event) { event.preventDefault();  window.location.href = 'YourHealth.aspx?find=Details'; }); var g1, g2, g3; var g1 = new JustGage({id: 'g1', value: getRandomInt(" + (int)Session["p1"] + ", " + (int)Session["p2"] + "), min: 0, max: 100,  title: 'Tu salud', label: 'Ver Detalles', gaugeWidthScale: 1.2, levelColors: ['#FF0E0E','#FCF700','#339900'] }); var g2 = new JustGage({ id: 'g2', value: getRandomInt(0, 100), min: 0, max: 100,  title: 'Tu planeta', label: 'Regular! :(',  gaugeWidthScale: 1.2, levelColors: [ '#FF0E0E', '#FCF700', '#339900'] }); var g3 = new JustGage({ id: 'g3', value: getRandomInt(0, 100),  min: 0, max: 100,  title: 'Tu comunidad',  label: 'Bien! :)', gaugeWidthScale: 1.2, levelColors: [ '#FF0E0E', '#FCF700', '#339900'] }); setInterval(function () { g1.refresh(getRandomInt(" + (int)Session["p1"] + ", " + (int)Session["p2"] + ")); g2.refresh(getRandomInt(0, 100)); g3.refresh(getRandomInt(0, 100)); }, 2500); });");

            if (details) { divDetails.Visible = true; divIngredients.Visible = false; } else { divDetails.Visible = false; divIngredients.Visible = true; }

            // yourHealthCircle.Attributes.Add("style", "background:#fff url('../img/body-back.png') repeat");


        }

        public void scriptm(string script)
        {

            ScriptManager.RegisterClientScriptBlock(
                    this,
                    typeof(Page),
                    "ToggleScript",
                    script,
                    true);

        }
    }
}